﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Windows.Forms;
using System.Diagnostics;

namespace Bakındur
{
    class SozlukBaslatici : Baslatici<string>
    {
        private WebClient client;

        public SozlukBaslatici()
        {
            client = new WebClient();
            client.Encoding = Encoding.UTF8;
        }

        private bool isBusy;
        public override bool IsBusy
        {
            get
            {
                return isBusy;
            }
            set
            {
                isBusy = value;
            }
        }

        public override string Command
        {
            get
            {
                return "http://m.seslisozluk.com/?word=";
            }
        }

        public override string Shortcut
        {
            get { return "s"; }
        }

        public override void Execute()
        {
            IsBusy = true;
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);

            try
            {
                client.DownloadStringAsync(new Uri(string.Format("{0}{1}", Command, Arguments)), "Sozluk");
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Web sayfası download edilirken hata oluştu: {0}", ex.Message));
                throw;
            }
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string fullHtml = e.Result.Replace("&nbsp;", "");

                int transStart = fullHtml.IndexOf("<div id=\"translations\">");
                int transEnd = fullHtml.LastIndexOf("<!-- id=translations -->");
                if (transStart > -1 && transEnd > -1)
                {
                    string onlyResult = fullHtml.Substring(transStart, transEnd - transStart);
                    result = onlyResult;
                }
                else
                    result = "Sonuç bulunamadı! Lütfen internet bağlantınızı kontrol edin.";

            }
            catch { throw; }
            IsBusy = false;
        }
    }
}
